<?php

App::uses('AppController', 'Controller');
/**
 * Apoiadores Controller
 *
 * @property Apoiadore $Apoiadore
 */
class GeonamesController extends GeonamesAppController {
	
	public function beforeFilter(){
		parent::beforeFilter();
		$this->Auth->allow('paises', 'estados', 'cidades');
	}
	
	public function paises(){
		$this->autoRender = false;
		$this->loadModel('Geonames.Pais');
		if(isset($this->request->query['query'])){
			$query = $this->request->query['query'];
			$dados = $this->Pais->find('all', array('conditions'=>array('language'=> getLanguage(), 'LOWER(countryName) LIKE'=>"%".strtolower($query)."%"), 'fields'=>array('geonameId', 'countryName', 'id')));
		}
		else
			$dados = $this->Pais->find('all', array('conditions'=>array('language'=> getLanguage()), 'fields'=>array('geonameId', 'countryName', 'id'), 'order'=>'countryName ASC'));
		//$dados = $this->Pais->find('all', array('conditions'=>array('language'=> 'pt', 'LOWER(countryName) LIKE'=>"%".strtolower($query)."%"), 'fields'=>array('countryName')));
		foreach($dados as $item){
			$return[] = $item['Pais'];
		}
		if(isset($return))
			return json_encode($return);
		return false;
	}
	
	private function finder($model){
		$parentId = $this->request->query['parentId'];
		$this->loadModel('Geonames.'.$model);
		if(isset($this->request->query['query'])){
			$query = $this->request->query['query'];
			$dados = $this->$model->find('all',
				array(
					'conditions'=>array(
						'language'=> getLanguage(),
						'LOWER(name) LIKE'=>"%".strtolower($query)."%",
						'geonameParentId'=>$parentId
					),
					'fields'=>array(
						'geonameId', 'name', 'id'
					)
				)
			);
		}
		else{
			$dados = $this->$model->find('all',
					array(
							'conditions'=>array(
									'language'=> getLanguage(),
									'geonameParentId'=>$parentId
							),
							'fields'=>array(
									'geonameId', 'name', 'id'
							),
							'order'=>'name'
					)
			);
		}
		foreach($dados as $item){
			$return[] = $item[$model];
		}
		if(isset($return))
			return json_encode($return);
		return false;
	}
	
	public function estados(){
		$model = 'RegiaoAdministrativa';
		$this->autoRender = false;
		return $this->finder($model);
	}
	
	public function cidades(){
		$model = 'Cidade';
		$this->autoRender = false;
		return $this->finder($model);
	}
	
}
